/*
filterer.js

Web worker. http://www.whatwg.org/specs/web-workers/current-work/

Handles Mercury filter requests.

This requires json.js - make sure you pack them together before deploying.
*/

// Begin normal stuff
var db = openDatabase('minerva.web.db', '1.0', 'Minerva DB', 1024*1024*5);

onmessage = function(event) {
  var spec = event.data;
  runFilter(spec); // runFilter will postMessage
  }


onerror = function(event) {
  var err = event.data;
  postMessage('ERROR: ' + err);
  }


// TODO: This whole thing needs to be cleaned up. Pretty much a hack atm.
var runFilter = function(spec) {
  // Derive new query result and render
  var params = JSON.parse(spec);
  var positionals = [];
  var clauses = '';

  var root = params.root;
  var types = params.types;
  var authors = params.authors;
  var keywords = params.keywords;

  var readWords = function(words) {
    var placeholders = [];
    for (var i=0; i<words.length; i++) {
      placeholders.push('?');
      positionals.push(words[i]);
      }
    return placeholders;
    };

  // First we do root
  if (root) {
    clauses += ' path like ? ';
    if (root[0] != '/') {
      root = '/' + root;
      }
    positionals.push(root + '%');
    }

  // Then keywords
  // Look for any one of the keywords in path
  if (keywords) {
    var words = keywords.split(' ');
    if (clauses) clauses += ' and ';
    clauses += '(';
    for (var i=0; i<words.length; i++) {
      if (i > 0) clauses += ' or ';
      clauses += ' path like ? ';
      positionals.push('%' + words[i] + '%');
      }
    clauses += ')';
    }

  // Then type
  if (types) {
    var words = types.split(' ');
    var placeholders = readWords(words);
    if (clauses) clauses += ' and ';
    clauses += ' type in (' + placeholders.join(',') + ') ';
    }

  // Then authors
  if (authors) {
    var words = authors.split(' ');
    var placeholders = readWords(words);
    if (clauses) clauses += ' and ';
    clauses += ' creator in (' + placeholders.join(',') + ') ';
    }

  if (clauses) {
    var result_html = '';
    db.transaction(function(tx) { 
      tx.executeSql(
        'select * from NounEvents where ' + clauses, positionals,
        function(tx, results) { 
          var len = results.rows.length;
          for (var i = 0; i < len; i += 1) {
            var path = results.rows.item(i).path;
            var title = results.rows.item(i).title;
            result_html += '<span id="' + path + '" class="mercury_result">' + 
                           title + '</span>';
          }
          result_html += '<div class="clearerer"></div>';
          postMessage(result_html);
        });
      });
    }
  };
